/**
 * webUploader 文件上传封装
 * Created by 301 on 2017/9/13.
 */

jQuery.fn.extend({
    sweetUp:function(o){
        var c = $.extend({
            swf: "/static/plugins/webuploader/0.1.7" + '/Uploader.swf',// swf文件路径
            server: "/uuuuu/upload",// 文件接收服务端。
            delurl : '/uuuuu/delete',// 文件删除服务端。
            formData:{},//请求json
            extensions: '*', //允许的文件后缀，不带点
            fileNumLimit:undefined,//文件总数量
            fileSizeLimit:undefined,//文件总大小,单位 字节（B）
            fileSingleSizeLimit:undefined,//单个文件大小,单位 字节（B）
            multiple:true,//是否同时可以选择多个文件
            hiddennames:'hiddennames',//文件隐藏域name
            chunked:false,//是否要分片处理大文件上传。
            chunkSize: 5242880,//如果要分片，分多大一片
            timeout: 2 * 60 * 1000,//超时时间，2分钟 
            isImg:true,//是否图片上传
            loddImg:'/static/plugins/webuploader/0.1.7/lodding.gif',
            fileIconImg:'/static/plugins/webuploader/0.1.7/fileIcon.png',
            initData:''
        },o);
        var $that = $(this);
        var $fileBox =   $( '<div  class="uploader-list"></div>' ); //listBox
        var $Picker =   $( '<div  class="filePicker">+</div>' ); //添加按钮
        function init(){
            $that.append( $fileBox ).append( $Picker );
            if(c.initData){initData(c.initData);}
            
        //单位转换
            if(c.fileSingleSizeLimit){
            if(c.fileSingleSizeLimit.indexOf('KB')!=-1){
            	c.fileSingleSizeLimit = parseInt(c.fileSingleSizeLimit) * 1024;
            } else if(c.fileSingleSizeLimit.indexOf('MB')!=-1){
            	c.fileSingleSizeLimit = parseInt(c.fileSingleSizeLimit) * 1024 * 1024 ;
            } else if(c.fileSingleSizeLimit.indexOf('GB')!=-1){
            	c.fileSingleSizeLimit = parseInt(c.fileSingleSizeLimit) * 1024 * 1024 * 1024;
            }
            }
        }
        //回显
        function initData(dataArr){
            dataArr = dataArr.split(",");
            $.each(dataArr,function(i,str){
                var $li = $('<div class="upfile-item upload-state-done">' +
                    '<img src= '+ fileIconIf(str) +' >' +
                    '<input type="hidden" value="'+str+'" id="'+c.hiddennames+'" name="'+c.hiddennames+'" />'+
                    operation(str)	
                );
                $fileBox.append( $li );
            })
        }
        //创建操作块
        function operation(_src){
            var operationele =
                '<div class="upfile-operation">'+
                '<a class="btn_view" href="'+ fileIconIf(_src) +'" target="_blank">查看</a>' +
                '<a class="btn_del" data-path="'+ _src +'"  href="javascript:;">删除</a>' +
                '</div>' ;
            var operationele1 =
                '<div class="upfile-operation">'+
                '<a class="btn_del" data-path="'+ _src +'"  href="javascript:;">删除</a>' +
                '</div>' ;
            if(c.isImg){
                return operationele;
            }
            return operationele1;
        }

        init();

        //添加文件创建LI
        function buildLi(file){
            var $li = $('<div id="' + file.id + '" class="upfile-item">' +
                '<img src='+ c.loddImg +' >' +
                '<input type="hidden" value="" id="'+c.hiddennames+'" name="'+c.hiddennames+'" />'+
                '<div class="upfile-info">' + file.name + '</div>' +
                '</div>'
            );
            $fileBox.append( $li );
        }
        //添加按钮显示与否
        function btnIf(){
        	 var ind = $fileBox.find('.upfile-item').length;
             if(ind>=c.fileNumLimit){
             	$Picker.hide();
             	return false;
             }
        }
      //文件图标与否
        function fileIconIf(str){
        	 if(c.isImg){
        		 return str;
        	 }
        	 return c.fileIconImg;
        }
        


        //初始化Web Uploader
        var uploader = WebUploader.create({
            auto: true,
            swf: c.swf,
            server: c.server,
            formData: c.formData,
            method:'POST',
            pick: {
                id:$Picker,
                multiple: c.multiple
            },
            timeout: c.timeout,
            accept : {
                extensions: c.extensions
            },
            fileNumLimit: c.fileNumLimit,//文件总数量
            fileSizeLimit: c.fileSizeLimit,//文件总大小
            fileSingleSizeLimit: c.fileSingleSizeLimit,//单个文件大小
            multiple: c.multiple,
            chunked: c.chunked,
            chunkSize: c.chunkSize,
        });

        
        // 添加之前
        uploader.on( 'beforeFileQueued', function( file ) {
        	btnIf()
        });

        // 文件进来
        uploader.on( 'fileQueued', function( file ) {
            buildLi(file);
            console.log(file)
            var $li = $( '#'+file.id ),
            $percent = $li.find('.progress');
	        if ( !$percent.length ) {
	            $percent = $('<span class="progress"></span>').appendTo( $li )
	        }
	      //生成电子书，定制lodding
        	if(c.isLod){ 
        		var lodUrl = c.isLod+'/'+file.name;
        		var lodInt = setInterval(hello,700);
        		function hello(){ 
           		 $.ajax({
                        url: lodUrl,
                        dataType: 'json',
                        success: function(data){
                       	 console.log(data)
                       	 $percent.html((data.code?data.code:0) +'%');
                       	 if(data.code=='100'){
                       		clearInterval(lodInt);
                       		var iinfohtml ='共：'+ data.uuid.split(',')[1]+'页, '+ (file.size/1024/1024).toFixed(1)+'MB';
                        	$li.find('.upfile-info').html(iinfohtml);
                        	$('input[name="docName"]').val(file.name.split('.')[0]);
                       	 }
                        }
                    });
           		
       		} 
        	}else{
	            uploader.md5File( file )
	
	            .progress(function(percentage) {
	                console.log('Percentage:', percentage);
	                $percent.html(parseInt(percentage*100) + '%' );
	            })

	            .then(function(val) {
	                console.log('md5 result:', val);
	                $percent.html(100 + '%' );
	            });
        	}
        });
     
      

        // 文件上传成功
        uploader.on( 'uploadSuccess', function( file , res) {
            $( '#'+file.id ).addClass('upload-state-done').append(operation(res.filePath)).find('img').attr('src',fileIconIf(res.filePath));
            $('input[name='+ c.hiddennames +']').val(res.filePath).attr({'data-size':Math.ceil(file.size/1024),'data-name':file.name})
            btnIf()
        });

        // 文件上传失败。
        uploader.on( 'uploadError', function( file ) {
            var $li = $( '#'+file.id );
            uploader.removeFile( file.id,true);
            $li.remove();
            $Picker.show();
        });

        // 完成上传完，成功或者失败。
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').remove();
        });
        // 上传错误。
        uploader.on( 'error', function( code ,file) {
          switch(code) {
          case 'F_EXCEED_SIZE':
        	  layer.msg("文件大小不符合规则！",{icon:2,time:2000});
              break;
          case 'Q_TYPE_DENIED':
        	  layer.msg("文件" +file.name + "类型不符合规则！",{icon:2,time:2000});
              break;
          case 'F_DUPLICATE':
        	  layer.msg("文件" +file.name + "已存在！",{icon:2,time:2000});
              break;
          case 'Q_EXCEED_NUM_LIMIT':
        	  layer.msg("选择文件数量超出规则！",{icon:2,time:2000});
              break;
          default:
        	  layer.msg("文件" +file.name + "上传出错！",{icon:2,time:2000});
      }
        });
        //图片删除
        $fileBox.on( 'click', '.btn_del', function() {
            var path=$(this).attr("data-path");
            var $obj = $(this).parents(".upfile-item");
            $.post(c.delurl,{"filePath":path},function(data){
            	if($obj.attr('id')){
            	 	uploader.removeFile( $obj.attr('id'),true );
            	}
                $obj.remove();
                $Picker.show();
            });
        } );
        btnIf()
       
    }
})
